/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.masterdata.material.controller;

import com.erp.dataset.service.DatasetCommonService;
import com.erp.masterdata.common.param.MasterDataParam;
import com.erp.masterdata.common.utils.ExcelUtils;
import com.erp.masterdata.common.utils.ReadExcelUtil;
import com.erp.masterdata.eco.service.MasterDataEcoService;
import com.erp.masterdata.material.dao.data.DataBox;
import com.erp.masterdata.material.dao.model.MdMaterial;
import com.erp.masterdata.material.dao.model.MdMaterialCO;
import com.erp.masterdata.material.dao.model.MdMaterialCategory;
import com.erp.masterdata.material.service.MdMaterialCategoryService;
import com.erp.masterdata.material.service.MdMaterialService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.hibernate.exception.ConstraintViolationException;
import org.redragon.framework.hibernate.data.RDDataBox;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.springmvc.ControllerSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/web/mdMaterial")
public class MdMaterialWebController extends ControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(MdMaterialWebController.class);
    
    //服务层注入
    @Autowired
    private MdMaterialService mdMaterialService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private MdMaterialCategoryService mdMaterialCategoryService;
    @Autowired
    private MasterDataEcoService masterDataEcoService;
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getMdMaterialList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2020-07-14 22:27:04
     * @author 
     * @param pages
     * @param mdMaterialCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getMdMaterialList")
    public String getMdMaterialList(Pages pages, MdMaterialCO mdMaterialCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        mdMaterialCO.setIsDel(MasterDataParam.IS_DEL_NO);
        //分页查询数据
        List<MdMaterial> mdMaterialList = this.mdMaterialService.getDataObjects(pages, mdMaterialCO);
        for(MdMaterial mdMaterial: mdMaterialList) {
          //获取物料类型
            MdMaterialCategory mdMaterialCategory = this.mdMaterialCategoryService.getDataObject(mdMaterial.getCategoryCode());
            if(mdMaterialCategory!=null) {
                mdMaterial.setCategoryDesc(mdMaterialCategory.getSegmentDesc());
            }
        }
        
        //获取物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        //获取物料或服务选择
        Map materialTypeMap = DataBox.getMaterialTypeMap();
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        
        //页面属性设置
        model.addAttribute("mdMaterialList", mdMaterialList);
        model.addAttribute("pages", pages);
        model.addAttribute("materialUnitMap", materialUnitMap);
        model.addAttribute("materialTypeMap", materialTypeMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        
        return "basic.jsp?content=mdMaterial/mdMaterialList";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2020-07-14 22:27:04
     * @author 
     * @param mdMaterial
     * @param model
     * @return String
     *
     */
    @RequestMapping("getMdMaterial")
    public String getMdMaterial(MdMaterial mdMaterial, Model model) {
        //查询要编辑的数据
        if(mdMaterial!=null&&mdMaterial.getMaterialId()!=null) {
            mdMaterial = this.mdMaterialService.getDataObject(mdMaterial.getMaterialId());
            //获取物料类型
            MdMaterialCategory mdMaterialCategory = this.mdMaterialCategoryService.getDataObject(mdMaterial.getCategoryCode());
            if(mdMaterialCategory!=null) {
                mdMaterial.setCategoryDesc(mdMaterialCategory.getSegmentDesc());
            }
        }
        
        //获取物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        //获取物料或服务选择
        Map materialTypeMap = DataBox.getMaterialTypeMap();
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //物料bom属性
        Map bomPropertyMap = DataBox.getBomPropertyMap();
        
        //页面属性设置
        model.addAttribute("mdMaterial", mdMaterial);
        model.addAttribute("materialUnitMap", materialUnitMap);
        model.addAttribute("materialTypeMap", materialTypeMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("bomPropertyMap", bomPropertyMap);
        
        return "basic.jsp?content=mdMaterial/mdMaterialEdit";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2020-07-14 22:27:04
     * @author 
     * @param mdMaterial
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editMdMaterial")
    public String editMdMaterial(@Valid MdMaterial mdMaterial, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        //参数校验
        Map<String, String> errorMap = this.validateParameters(bindingResult, model);
        if(errorMap.size()>0) {
            return "forward:getMdMaterial";
        }
        try {
            //对当前编辑的对象初始化默认的字段
            
            //保存编辑的数据
            this.mdMaterialService.insertOrUpdateDataObject(mdMaterial);
            //提示信息
            attr.addFlashAttribute("hint", "success");
        }catch(Exception e){
            if(e.getCause().getClass()==ConstraintViolationException.class) {
                //提示信息
                model.addAttribute("hint", "hint");
                model.addAttribute("alertMessage", "编码已存在，请重新输入");
                return "forward:getMdMaterial";
            }else {
                throw e;
            }
        }
        
        return "redirect:getMdMaterialList";
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2020-07-14 22:27:04
     * @author 
     * @param mdMaterial
     * @return String
     *
     */
    @RequestMapping("deleteMdMaterial")
    public String deleteMdMaterial(MdMaterial mdMaterial, RedirectAttributes attr) {
        //删除数据前验证数据
        if(mdMaterial!=null&&mdMaterial.getMaterialId()!=null) {
            mdMaterial = mdMaterialService.getDataObject(mdMaterial.getMaterialId());
            mdMaterial.setIsDel(MasterDataParam.IS_DEL_YES);
            //逻辑删除
            mdMaterialService.insertOrUpdateDataObject(mdMaterial);
            //删除数据
//            this.mdMaterialService.deleteDataObject(mdMaterial);
            //提示信息
            attr.addFlashAttribute("hint", "success");
        }
        
        return "redirect:getMdMaterialList";
    }
    
    
    
    /**
     * 
     * @description 更新审批状态
     * @date 2020年8月4日
     * @author dongbin
     * @param id
     * @param approveStatus
     * @param attr
     * @return
     * @return String
     *
     */
    @RequestMapping("updateApproveStatus")
    public String updateApproveStatus(Integer id, String approveStatus, RedirectAttributes attr) {
        
        if(id!=null&&StringUtils.isNotBlank(approveStatus)) {
            
            if(approveStatus.equals("UNSUBMIT")) {
                //ECO===记录变更历史数据
                int errorCode = this.masterDataEcoService.saveMdHistoryData("md_material", "material_id", id.toString());
                
                if(errorCode!=0) {
                    //提示信息
                    attr.addFlashAttribute("hint", "hint");
                    attr.addFlashAttribute("alertMessage", "当前物料或服务保存变更历史错误，无法变更");
                    attr.addAttribute("materialId", id);
                    return "redirect:getMdMaterial";
                }
            }
            
            //更新审核状态
            this.mdMaterialService.updateApproveStatus(id, approveStatus);
          //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("materialId", id);
        }else {
            //提示信息
            attr.addFlashAttribute("hint", "hint");
            attr.addFlashAttribute("alertMessage", "提交或审批数据错误");
            attr.addAttribute("materialId", id);
        }
        
        return "redirect:getMdMaterial";
    }

    /**
     * 通过excel文件，批量增加课程
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/upload/material")
    @ResponseBody
    public String uploadCourseExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartHttpServletRequest.getFile("courseFile");
        List<ArrayList<String>> readExcel = new ArrayList<>();
        try {
            //调用util方法拿到解析的数据集合
            readExcel = new ReadExcelUtil().readExcel(file);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //获取文件名后缀
        String postfix = ExcelUtils.getPostfix(file.getOriginalFilename());
        //获取文件名
        String originalFileName = file.getOriginalFilename();
        int beginIndex = originalFileName.lastIndexOf(".");
        //原名
        String fileName = originalFileName.substring(0,beginIndex);
        //调用service层业务接口实现Excel文件整理和创建
        List<MdMaterial> newDoList  = mdMaterialService.excelEmportFile(readExcel, fileName, postfix);
        if(newDoList.size() == 0){
            return "{\"result\":\"success\", \"message\": \"批量添加成功！\"}";
        }else{
            return "{\"result\":\"error\", \"message\": \"共" + newDoList.size() + "数据没有导入失败！\"}";
        }
        // 响应到客户端
//        try {
//            fileName = fileName + "_错误数据." + postfix;
//            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//            wb.write(outputStream);
//            ByteArrayInputStream tempIn = new ByteArrayInputStream(outputStream.toByteArray());
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setHeader("Content-Length", String.valueOf(tempIn.available()));
//            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
//            response.addHeader("Content-type", "application-download");
//            response.setContentType("application/octet-stream");
//            ServletOutputStream out = response.getOutputStream();
//            BufferedOutputStream toOut = new BufferedOutputStream(out);
//            byte[] buffer = new byte[tempIn.available()];
//            int a;
//            while ((a = tempIn.read(buffer)) != -1) {
//                out.write(buffer, 0, a);
//            }
//            toOut.write(buffer);
//            toOut.flush();
//            out.flush();
//            out.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return "{\"result\":\"error\", \"message\": \"部分数据没有导入成功\"}";
    }

    /**
     *
     * @description 查询数据列表
     * @date 2020-07-14 22:27:04
     * @author
     * @param mdMaterialCO
     * @return String
     *
     */
    @RequestMapping("/getMdMaterialListByCO")
    @ResponseBody
    public List<MdMaterial> getMdMaterialListByCO(MdMaterialCO mdMaterialCO) {
        mdMaterialCO.setIsDel(MasterDataParam.IS_DEL_NO);
        //分页查询数据
        return this.mdMaterialService.getDataObjects(mdMaterialCO);
    }


}
